<?php

class User {
	
	private $username;
	private $passwordEncrypted;
	private $passwordTemporary;
	private $expireDate;
	
	public function __construct($username, $password, $isCookiesSet) {
		$this->username = $username;
		
		if ($isCookiesSet) {
			$this->passwordTemporary = $password;
			$parts = explode("><", $this->passwordTemporary);
			$this->passwordEncrypted = $parts[0];
			$this->expireDate = $parts[1];
		}
		else {
			$this->passwordEncrypted = md5($password);
			$this->createNewPasswordTemporary();
		}
	}
	
	public function isSame(User $other) {
		if ($this->username == $other->username) {
			return true;
		}
		return false;
	}
	
	public function matchPasswords($password) {
		return !(strcmp($this->passwordEncrypted, $password) != 0);
	}
	
	public function matchExpireDate($expireDate) {
		return !(time() > $expireDate);
	}
	
	public function createNewPasswordTemporary() {
		$this->passwordTemporary = $this->passwordEncrypted . "><" . $this->createNewExpireDate();
	}
	
	public function createNewExpireDate() {
		return $this->expireDate = time() + 20;
	}
	
	public function getUsername() {
		return $this->username;
	}
	
	public function getPasswordEncrypted() {
		return $this->passwordEncrypted;
	}
	
	public function getPasswordTemporary() {
		return $this->passwordTemporary;
	}
	
	public function getExpireDate() {
		return $this->expireDate;
	}
	
	public function toString() {
        return $this->username . "<>" . $this->passwordTemporary;
	}
	
    public static function fromString($string) {
        $parts = explode("<>", $string);
        return new User($parts[0], $parts[1], true);
    }
	
}
